import { getCookie } from '@inbiz/utils';
import {request} from '@inbiz/utils';
const version = InbizConfig.API_VERSION;
import type { MutableRefObject } from 'react';
import { TransferProps } from '.';

const canvert = (data: any, id: string) => {
  return data.map((item: any) => {
    if (id.includes('$')) {
      item[id.split('$')[1]] = item[id.split('$')[1]]?.toString?.();
    } else {
      item[id] = item[id]?.toString?.();
    }
    if (item.child) {
      item.child = canvert(item.child, id);
    }
    return item;
  });
};

export function getTreeData(params: {
  appId: string;
  id: string;
  sourceKey: string;
  parentId: string;
  value: string | number;
}): Promise<any> {
  const { appId, id, ...rest } = params;
  if (!params.id) {
    return Promise.resolve([]);
  }
  return request(`/inbiz/api/services/front/modelengine/v${version}/assembly/treeDatas/${appId}`, {
    params: {
      ...rest,
      id: id.split('$')[0],
      token: getCookie('token'),
    },
  }).then((res) => {
    let newRes;
    if (res?.Data?.length) {
      newRes = canvert(res?.Data, params.id);
    }
    return { data: params.value === 0 ? newRes : newRes[0].child || [] };
  }); // 强行包装一个只有一个元素的 Data 数组，接口问题
}

export function getTableData(params: {
  appId: string;
  id: string;
  sourceKey: string;
  pageIndex: number;
  pageSize: number;
  parentId?: string;
  value?: string | number;
  searchValue?: string;
  searchKey?: string;
}) {
  const { appId, ...rest } = params;
  if (!params.id) {
    return Promise.resolve({ data: [] });
  }
  if (rest.searchValue === '' || rest.searchValue === undefined) {
    delete rest.searchKey;
  }
  return request(`/inbiz/api/services/front/modelengine/v${version}/assembly/treeDatas/${appId}`, {
    params: {
      ...rest,
      token: getCookie('token'),
    },
  }).then((res) => ({
    totalCount: res.TotalCount,
    pageIndex: res.PageIndex,
    pageSize: res.PageSize,
    pageCount: res.PageCount,
    data: res.Data,
  }));
}

export function getModelData(params: { appId: string }): Promise<
  {
    Children: any[];
    IsMany: boolean;
    ModelKey: string;
    ModelName: string;
    ParentModelKey: string;
  }[]
> {
  return request(`/inbiz/api/services/modelengine/v${version}/model/manys/${params.appId}`);
}

export function getListData(params: {
  appId: string;
  key: string;
  modelName: string;
  ids: (string | number)[];
  field: string;
}) {
  const { appId, ids, key, modelName, field } = params;
  return request
    .post(`/inbiz/api/services/front/modelengine/v${version}/modelQueryAdapter/queryDatas`, {
      data: {
        key,
        conditions: [
          {
            index: 0,
            condition: ids.map((id) => ({
              field: field.split('$')[0],
              modelName,
              connector: 1,
              operator: 0,
              value: id,
            })),
            connector: 0,
          },
        ],
        appId,
      },
    })
    .then((res) => {
      if (res?.Rows?.length) {
        return canvert(res?.Rows, field);
        // res.Rows.map((item: { id: string }) => {
        //   if (item[field.split('$')[1]]) {
        //     item[field.split('$')[1]] = item[field.split('$')[1]].toString();
        //   }
        // });
        // return res.Rows;
      }
      return [];
    });
}

type events = MutableRefObject<TransferProps['callBackEvents']>;
type Service<TData, TParams extends any> = (args: TParams) => Promise<TData>;

export function apiWrapper<TParams, TData, E extends events>(
  fn: Service<TData, TParams>,
  events: E,
  fieldNames: {
    onParamFormat: string;
    onData: string;
    onRequest: string;
  },
) {
  const { onParamFormat, onData, onRequest } = fieldNames;
  return function (args: Parameters<typeof fn>[number]) {
    let reqArgs = args;
    if (events.current?.[onParamFormat]) {
      reqArgs = events.current[onParamFormat](reqArgs);
    }
    const reqFn = (events.current?.[onRequest] as typeof fn) || fn;
    return reqFn(reqArgs).then((res) => {
      if (events.current?.[onData]) {
        return events.current[onData](res) as TData;
      } else {
        return res;
      }
    });
  };
}

export async function getDocumentInfo(docmentIds: string, props: any) {
  let url = '';
  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return Promise.resolve(docmentIds.split(',') ?? []);
  } else if (props.childModelConfig) {
    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        return list;
      });
  }
  return undefined;
}
